<?php
require_once(dirname(__FILE__).'/Abstract.php');
class ConsultationMetier extends AbstractConsultationMetier 
{
    /**
     * Consultation::getMessages()
     * Get messages sent through the system
     * 
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_doctor            => default = null (any doctor)                 // Messages including this doctor
     *      id_patient           => default = null (any patient)                // Messages includind this patient
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     *      toDoctor|toPatient   => default = null (to both doctor and patient) // Messages sent to the doctor or to the patient
     *      notReaded            => default = null (both readed or not readed)  // Messages readed by the receiver
     *      notDeleted           => default = null (Deleted and not deleted)    // Messages not deleted by the sender or the receiver [sender|receiver|both]
     * )
     * @return messages
     */
    public function getMessages ($config = array())
    {
        $chat            = isset($config['chat']) ? ($config['chat'] ? 'chat' : 'offline') : null;                        
        $id_doctor       = !empty($config['id_doctor']) ? (int)$config['id_doctor'] : null;    
        $id_patient      = !empty($config['id_patient']) ? (int)$config['id_patient'] : null;  
        $id_consultation = !empty($config['id_consultation']) ? (int)$config['id_consultation'] : null;
        $id_message      = !empty($config['id_message']) ? (int)$config['id_message'] : null;
        $from            = !empty($config['toDoctor']) ? 'patient' : (!empty($config['toPatient']) ? 'doctor' : null);
        $readed          = isset($config['notReaded']) ? ($config['notReaded'] ? 0 : 1) : null;
        if (isset($config['notDeleted'])) {
            switch ($config['notDeleted']) {
                case 'both'     : $delete = '00'; break;
                case 'sender'   : $delete = 'LIKE \'_0\''; break;
                case 'receiver' : $delete = 'LIKE \'0_\''; break;
                default : $delete = null; break;
            }
        } else {
            $delete = null;
        }
        
        $query = $this->db->query('
            SELECT msg.*, 
            
                   CONCAT(LEFT(doctor_entity.`firstname`, 1), \'. \', doctor_entity.`lastname`) AS doctor_name, doctor_entity.`email` AS doctor_email,
                   doctor.`medical_id` AS doctor_medical_id, doctor.`phone` AS doctor_phone, doctor.`profession` AS doctor_profession, 
                   doctor.`address` AS doctor_address, doctor.`description` AS doctor_description, 
                   
                   CONCAT(LEFT(patient_entity.`firstname`, 1), \'. \', patient_entity.`lastname`) AS patient_name, patient_entity.`email` AS patient_email,
                   patient.`birthday` AS patient_birthday, patient.`phone` AS patient_phone, patient.`profession` AS patient_profession, patient_entity.`id_user` AS patient_id, 
                   patient.`pobox` AS patient_pobox, patient.`town` AS patient_town, patient.`nb_secur_social` AS patient_nb_secur_social, 
                   patient.`cmu` AS patient_cmu, patient.`address` AS patient_address
            FROM `medic_consultation_message` `msg`
            LEFT JOIN `medic_consultation` cons ON (msg.`id_consultation` = cons.`id_consultation`)
            LEFT JOIN `medic_user_doctor` doctor ON (cons.`id_doctor` = doctor.`id_doctor`)
            LEFT JOIN `medic_user_entity` doctor_entity ON (doctor.`id_user` = doctor_entity.`id_user`)
            LEFT JOIN `medic_user_patient` patient ON (cons.`id_patient` = patient.`id_patient`)
            LEFT JOIN `medic_user_entity` patient_entity ON (patient.`id_user` = patient_entity.`id_user`)
            WHERE 1 '. 
            ($chat ? ' AND msg.`context` = \''.pSQL($chat).'\'' : '') .
            ($id_doctor ? ' AND cons.`id_doctor` = '.($id_doctor) : '') .
            ($id_patient ? ' AND cons.`id_patient` = '.($id_patient) : '') .
            ($from ? ' AND msg.sender = \''. pSQL($from) .'\'' : '') .
            ($readed ? ' AND msg.`readed` = '.($readed) : '') .
            ($delete ? ' AND msg.`deleted` '.($delete) : '') .
            ($id_message ? ' AND msg.`id_message` ='.($id_message) : '') .'
        ');
        
        return $query->result();
    }
    
    /**
     * Consultation::getMessagesToDoctor()
     * Get message sent to a doctor
     * 
     * @param mixed $id_doctor
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_patient           => default = null (any patient)                // Messages includind this patient
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     *      notReaded            => default = null (both readed or not readed)  // Messages readed by the receiver
     * @return
     */
    public function getMessagesToDoctor ($id_doctor, $config = array())
    {
        $config = array_merge($config, array('id_doctor'=>$id_doctor, 'toDoctor'=>true, 'notDeleted'=>'receiver'));
        return $this->getMessages($config);
    }
    
    /**
     * Consultation::getMessagesFromDoctor()
     * Get messages sent by a doctor
     * 
     * @param mixed $id_doctor
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_patient           => default = null (any patient)                // Messages includind this patient
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     * @return messages
     */
    public function getMessagesFromDoctor ($id_doctor, $config = array())
    {
        $config = array_merge($config, array('id_doctor'=>$id_doctor, 'toPatient'=>true, 'notDeleted'=>'sender', 'notReaded' => null));
        return $this->getMessages($config);
    }
    
    /**
     * Consultation::getMessagesToPatient()
     * Get messages sent to a patient
     * 
     * @param mixed $id_patient
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_doctor            => default = null (any doctor)                 // Messages including this doctor
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     *      notReaded            => default = null (both readed or not readed)  // Messages readed by the receiver
     * @return messages
     */
    public function getMessagesToPatient ($id_patient, $config = array())
    {
        $config = array_merge($config, array('id_patient'=>$id_patient, 'toPatient'=>true, 'notDeleted'=>'receiver'));
        return $this->getMessages($config);
    }
    
    /**
     * Consultation::getMessagesFromPatient()
     * Get messages sent by a patient
     * 
     * @param mixed $id_patient
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_doctor            => default = null (any doctor)                 // Messages including this doctor
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     * @return messages
     */
    public function getMessagesFromPatient ($id_patient, $config = array())
    {
        $config = array_merge($config, array('id_patient'=>$id_patient, 'toDoctor'=>true, 'notDeleted'=>'sender', 'notReaded' => null));
        return $this->getMessages($config);
    }

    /**
     * Consultation::getMessageByIdFromPatient()
     * Get message by id
     * 
     * @param mixed $id_message
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_doctor            => default = null (any doctor)                 // Messages including this doctor
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     * @return messages
     */
    public function getMessageByIdFromPatient ($id_message, $config = array())
    {
        $config = array_merge($config, array('id_message'=>$id_message/*, 'toDoctor'=>true, 'notDeleted'=>'sender', 'notReaded' => null*/));
        return $this->getMessages($config);
    }

    /**
     * Consultation::getMessageByIdFromDoctor()
     * Get message by id
     * 
     * @param mixed $id_message
     * @param mixed $config array(
     *      chat                 => default = null (both chat and offline)      // For messages of chat or offline messages
     *      id_doctor            => default = null (any doctor)                 // Messages including this doctor
     *      id_consultation      => default = null (any consultation)           // Messages for a specfic consultation
     * @return messages
     */
    public function getMessageByIdFromDoctor ($id_message, $config = array())
    {
        $config = array_merge($config, array('id_message'=>$id_message/*, 'toDoctor'=>true, 'notDeleted'=>'sender', 'notReaded' => null*/));
        return $this->getMessages($config);
    }

    public function getConnectedPatients($config = array())
    {
        $query = $this->db->query('
            SELECT  CONCAT(LEFT(patient_entity.`firstname`, 1), \'. \', patient_entity.`lastname`) AS patient_name, patient_entity.`email` AS patient_email,
                    patient.`birthday` AS patient_birthday, patient.`phone` AS patient_phone, patient.`profession` AS patient_profession, patient_entity.`id_user` AS patient_id, 
                    patient.`pobox` AS patient_pobox, patient.`town` AS patient_town, patient.`nb_secur_social` AS patient_nb_secur_social, 
                    patient.`cmu` AS patient_cmu, patient.`address` AS patient_address,

                    CONCAT(LEFT(doctor_entity.`firstname`, 1), \'. \', doctor_entity.`lastname`) AS doctor_name, doctor_entity.`email` AS doctor_email,
                    doctor.`medical_id` AS doctor_medical_id, doctor.`phone` AS doctor_phone, doctor.`profession` AS doctor_profession, 
                    doctor.`address` AS doctor_address, doctor.`description` AS doctor_description,

                     cons.*, cons_type.*, cons_type_lang.*, MAX(cons_history.`id_status`) AS max_id_status,  cons_status.*, cons_status_lang.*
                   
                FROM `medic_user_patient` `patient`
                LEFT JOIN `medic_user_entity` patient_entity ON (patient.`id_user` = patient_entity.`id_user`)
                LEFT JOIN `medic_consultation` cons ON (patient.`id_patient` = cons.`id_patient`)
                LEFT JOIN `medic_user_doctor` doctor ON (cons.`id_doctor` = doctor.`id_doctor`)
                LEFT JOIN `medic_user_entity` doctor_entity ON (doctor.`id_user` = doctor_entity.`id_user`)            
                LEFT JOIN `medic_consultation_type` cons_type ON (cons.`id_type` = cons_type.`id_type`)
                LEFT JOIN `medic_consultation_type_lang` cons_type_lang ON (cons_type.`id_type` = cons_type_lang.`id_type` AND cons_type_lang.`lang` = \''.$this->session->userdata('lang').'\')
                LEFT JOIN `medic_consultation_history` cons_history ON (cons.`id_consultation` = cons_history.`id_consultation`)
                LEFT JOIN `medic_consultation_status` cons_status ON (cons_history.`id_status` = cons_status.`id_status`)
                LEFT JOIN `medic_consultation_status_lang` cons_status_lang ON (cons_status.`id_status` = cons_status_lang.`id_status` AND cons_status_lang.`lang` = \''.$this->session->userdata('lang').'\')
                
            WHERE 1 
                GROUP BY cons.`id_consultation`
        ');

        return $query->result();
    }

    public function getConsultations($config = array())
    {

        $id_doctor       = !empty($config['id_doctor']) ? (int)$config['id_doctor'] : null;    
        $id_patient      = !empty($config['id_patient']) ? (int)$config['id_patient'] : null;  
        $id_consultation = !empty($config['id_consultation']) ? (int)$config['id_consultation'] : null;

        $query = $this->db->query('
            SELECT  CONCAT(LEFT(patient_entity.`firstname`, 1), \'. \', patient_entity.`lastname`) AS patient_name, 
            patient_entity.`email` AS patient_email,
            patient_entity.`is_connected` AS patient_is_connected,
            patient.`birthday` AS patient_birthday, patient.`phone` AS patient_phone, 
            patient.`profession` AS patient_profession, patient_entity.`id_user` AS patient_id, 
            patient.`pobox` AS patient_pobox, patient.`town` AS patient_town, 
            patient.`nb_secur_social` AS patient_nb_secur_social, 
            patient.`cmu` AS patient_cmu, patient.`address` AS patient_address,

            CONCAT(LEFT(doctor_entity.`firstname`, 1), \'. \', doctor_entity.`lastname`) AS doctor_name, 
            doctor_entity.`email` AS doctor_email,
            doctor_entity.`is_connected` AS doctor_is_connected,
            doctor.`medical_id` AS doctor_medical_id, 
            doctor.`phone` AS doctor_phone, doctor.`profession` AS doctor_profession, 
            doctor.`address` AS doctor_address, doctor.`description` AS doctor_description,
            
            cons.*, 

            @id_consultation:=cons.`id_consultation`,
            cons_type.tarif AS cons_tarif, 
            cons_type.duration AS cons_duration, 
            cons_type_lang.label AS cons_type_label, 
            cons_type_lang.description AS cons_type_description,

            @last_id_history:=(SELECT MAX(`id_history`) AS last_id_history FROM `medic_consultation_history` WHERE `id_consultation` = @id_consultation) AS last_id_history,

            cons_status.id_status AS cons_status_id, 

            cons_status_lang.label AS cons_status_label, cons_status_lang.lang AS cons_status_lang
       
            FROM `medic_consultation` cons
            
            LEFT JOIN `medic_user_patient` `patient` ON (patient.`id_patient` = cons.`id_patient`)
            LEFT JOIN `medic_user_entity` patient_entity ON (patient.`id_user` = patient_entity.`id_user`)

            LEFT JOIN `medic_user_doctor` doctor ON (cons.`id_doctor` = doctor.`id_doctor`)
            LEFT JOIN `medic_user_entity` doctor_entity ON (doctor.`id_user` = doctor_entity.`id_user`)

            LEFT JOIN `medic_consultation_type` cons_type ON (cons.`id_type` = cons_type.`id_type`)
            LEFT JOIN `medic_consultation_type_lang` cons_type_lang ON (cons_type.`id_type` = cons_type_lang.`id_type` AND  cons_type_lang.`lang` = \''.$this->session->userdata('lang').'\')
            
            LEFT JOIN `medic_consultation_history` cons_history ON (cons_history.`id_history` = @last_id_history)

            LEFT JOIN `medic_consultation_status` cons_status ON (cons_history.`id_status` = cons_status.`id_status`)
            LEFT JOIN `medic_consultation_status_lang` cons_status_lang ON (cons_history.`id_status` = cons_status_lang.`id_status` AND cons_status_lang.`lang` = \''.$this->session->userdata('lang').'\')
            
        WHERE 1 '.
            ($id_doctor ? ' AND cons.`id_doctor` = '.($id_doctor) : '') .
            ($id_patient ? ' AND cons.`id_patient` = '.($id_patient) : '') .
            ($id_consultation ? ' AND cons.`id_consultation` = \''.($id_consultation) .'\'' : '') .'
        
        GROUP BY cons.`id_consultation`
        ');

        return $query->result();
    }

    public function getConsultationsTypes($config = array())
    {   
        $id_type       = !empty($config['id_type']) ? (int)$config['id_type'] : null;

        $this->db->select('*');
        $this->db->from('medic_consultation_type');
        $this->db->join('medic_consultation_type_lang', 'medic_consultation_type.id_type = medic_consultation_type_lang.id_type AND medic_consultation_type_lang.lang = \''.$this->session->userdata('lang').'\'', 'LEFT');
        if ($id_type):
            $this->db->where('medic_consultation_type.id_type', '1');
            $query = $this->db->get();
            return $query->row_array();
        else:
            $query = $this->db->get();
            return $query->result();
        endif;
        
    }

    public function getAllDoctors()
    {   

        $this->db->select('*');
        $this->db->from('medic_user_entity');
        $this->db->join('medic_user_doctor', 'medic_user_doctor.id_user = medic_user_entity.id_user', 'LEFT');
        $this->db->where('medic_user_entity.id_role', 3);
        $query = $this->db->get();
        return $query->result();
    }


}

